# -*- coding: utf-8 -*-
'''
@Time    : 2021/5/4 18:49
@Author  : xiaojie
@File    : pyMysql.py
'''



import pymysql
import os

#from xiaojie.HomeWork18.dbinfo import dbinfo
from dbinfo import dbinfo



# print(os.getcwd())
# dbinfo = {
#     'host': '49.233.39.160',
#     'port': 3306,
#     'user': 'user',
#     'password': 'leboAa!#$123',
#     'database': 'lebo16',
#     'charset': 'utf8',
# }

# from xiaojie.HomeWork18 import test_date


print(os.getcwd())
dbinfo = {
    'host': '49.233.39.160',
    'port': 3306,
    'user': 'user',
    'password': 'leboAa!#$123',
    'database': 'lebo16',
    'charset': 'utf8',
}


class DataBase(object):

    def __init__(self,
                 host=dbinfo['host'],
                 port=dbinfo['port'],
                 user=dbinfo['user'],
                 password=dbinfo['password'],
                 database=dbinfo['database'],
                 charset=dbinfo['charset']):
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.database = database
        self.charset = charset

    # 获取数据库连接方法，返回值为游标
    def get_connect(self):
        if not self.database:
            raise RuntimeError('数据库没有找到')
        try:
            self.conn = pymysql.connect(host=self.host,
                                        port=self.port,
                                        user=self.user,
                                        password=self.password,
                                        database=self.database,
                                        charset=self.charset)
        except Exception as e:
            raise RuntimeError('初始化数据库失败，原因是：', e)

        self.cursor = self.conn.cursor()
        return self.cursor

    # 执行数据库sql语句操作
    def execute_sql(self, sql, params=None):
        self.get_connect()  # 连接数据库
        self.cursor.execute(sql, params)  # 发送语句
        self.conn.commit()  # 事务提交
        print('提交成功')


    def close_sql(self):
        try:
            if self.cursor:
                self.cursor.close()
                print('关闭游标成功')

            if self.conn:
                self.conn.close()
                print('关闭数据连接成功')
        except Exception as e:
            print("关闭游标或数据库异常，失败原因为：", e)


    def select_sql(self, sql, params=None):
        self.get_connect()
        self.execute_sql(sql, params)
        date = self.cursor.fetchall()
        return date

print(666)

if __name__ == '__main__':
    # db1 = DataBase("49.233.39.160", 3306, "user", "leboAa!#$123", "lebo16", "utf8")
    db1 = DataBase()
    sql = 'select * from students_0922'
    print(db1.select_sql(sql))
    print('sdsfds')
